# coding: utf-8
# @Time    : 2023/12/18 17:28
# @Author  : gongshuangxi
# @Email   : sxgong@topdatasec.com

import os
import logging
# pip install ConcurrentLogHandler
from cloghandler import ConcurrentRotatingFileHandler
#from loguru import logger

# 日志级别
LOG_LEVEL_DICT = {
    'critical':logging.CRITICAL,
    'error':logging.ERROR,
    'warning':logging.WARNING,
    'info':logging.INFO,
    'debug':logging.DEBUG
}


"""
log_switch: 日志开关
log_dir: 日志存放目录
log_filename: 日志文件名
log_level: 日志级别
max_bytes: 日志文件最大字节数
backup_count: 日志文件备份个数
"""
def process_logger(log_switch, log_dir, log_filename, log_level, max_bytes, backup_count):
    # 判断存放日志的文件夹是否存在 如果不存在新建
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    # 存放log的文件名
    log_filename = os.path.join(log_dir, log_filename)

    debug = False
    if log_switch:
        debug = True

    loglevel = LOG_LEVEL_DICT.get(log_level)
    if loglevel is None:
        loglevel = logging.ERROR

    # 创建一个logger
    logger = logging.getLogger(log_filename)
    # 设置日志等级
    logger.setLevel(loglevel)
    # 创建一个滚动日志处理器
    crfh = ConcurrentRotatingFileHandler(log_filename, mode='a', maxBytes=max_bytes, backupCount=backup_count,
                                         debug=debug, encoding='utf-8')
    # 定义handler的输出格式
    # 设定日志输出格式
    formatter = logging.Formatter('%(asctime)s [%(filename)s:%(lineno)d] [%(levelname)s] %(message)s')
    crfh.setFormatter(formatter)
    # 添加日志处理器
    logger.addHandler(crfh)
    # 返回logger对象

    #logger.add("logs/logfile.log", rotation="500 MB", compression="zip")
    return logger
